"""
主仪表板
AIQuant系统的主要Web界面，提供系统概览和快速导航
"""

import streamlit as st
import asyncio
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
from typing import Dict, Any, List
import httpx

from .components.metrics import MetricsCard
from .components.charts import create_line_chart, create_gauge_chart
from .components.common import load_css, get_system_status
from ..config.settings import settings


def main():
    """主仪表板页面"""
    st.set_page_config(
        page_title="AIQuant - 量化投研系统",
        page_icon="📈",
        layout="wide",
        initial_sidebar_state="expanded"
    )
    
    # 加载自定义CSS
    load_css()
    
    # 页面标题
    st.title("🚀 AIQuant 量化投研系统")
    st.markdown("---")
    
    # 系统状态检查
    system_status = get_system_status()
    
    # 顶部指标卡片
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        MetricsCard(
            title="系统状态",
            value="运行中" if system_status["healthy"] else "异常",
            delta="正常" if system_status["healthy"] else "需要关注",
            delta_color="normal" if system_status["healthy"] else "inverse"
        )
    
    with col2:
        MetricsCard(
            title="活跃智能体",
            value=f"{system_status.get('active_agents', 0)}",
            delta=f"共{system_status.get('total_agents', 25)}个",
            delta_color="normal"
        )
    
    with col3:
        MetricsCard(
            title="运行工作流",
            value=f"{system_status.get('running_workflows', 0)}",
            delta="实时处理",
            delta_color="normal"
        )
    
    with col4:
        MetricsCard(
            title="数据更新",
            value=system_status.get('last_update', '未知'),
            delta="实时同步",
            delta_color="normal"
        )
    
    st.markdown("---")
    
    # 主要功能区域
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.subheader("📊 系统性能监控")
        
        # 创建性能图表
        performance_data = get_performance_data()
        if performance_data:
            fig = create_line_chart(
                data=performance_data,
                x_col="timestamp",
                y_col="cpu_usage",
                title="CPU使用率",
                color="#1f77b4"
            )
            st.plotly_chart(fig, use_container_width=True)
        else:
            st.info("正在加载性能数据...")
    
    with col2:
        st.subheader("🎯 系统健康度")
        
        # 系统健康度仪表盘
        health_score = calculate_health_score(system_status)
        fig = create_gauge_chart(
            value=health_score,
            title="系统健康度",
            max_value=100
        )
        st.plotly_chart(fig, use_container_width=True)
        
        # 服务状态列表
        st.subheader("🔧 服务状态")
        services = system_status.get("services", {})
        for service, status in services.items():
            status_icon = "✅" if status == "running" else "❌"
            st.write(f"{status_icon} {service}: {status}")
    
    st.markdown("---")
    
    # 快速操作区域
    st.subheader("⚡ 快速操作")
    
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        if st.button("📊 数据管理", use_container_width=True):
            st.switch_page("pages/data_management.py")
    
    with col2:
        if st.button("🎯 策略管理", use_container_width=True):
            st.switch_page("pages/strategy_management.py")
    
    with col3:
        if st.button("💹 交易监控", use_container_width=True):
            st.switch_page("pages/trading_monitor.py")
    
    with col4:
        if st.button("📈 持仓分析", use_container_width=True):
            st.switch_page("pages/portfolio_analysis.py")
    
    # 最近活动
    st.markdown("---")
    st.subheader("📝 最近活动")
    
    recent_activities = get_recent_activities()
    if recent_activities:
        df = pd.DataFrame(recent_activities)
        st.dataframe(df, use_container_width=True)
    else:
        st.info("暂无最近活动记录")
    
    # 系统信息
    with st.expander("ℹ️ 系统信息"):
        col1, col2 = st.columns(2)
        
        with col1:
            st.write("**系统版本:** 1.0.0")
            st.write("**部署环境:** " + settings.environment)
            st.write("**启动时间:** " + system_status.get('start_time', '未知'))
        
        with col2:
            st.write("**智能体数量:** 25")
            st.write("**工作流类型:** 4")
            st.write("**协调模式:** 5")


def get_performance_data() -> List[Dict[str, Any]]:
    """获取系统性能数据"""
    try:
        # 模拟性能数据
        now = datetime.now()
        data = []
        for i in range(24):
            timestamp = now - timedelta(hours=i)
            data.append({
                "timestamp": timestamp,
                "cpu_usage": 20 + (i % 10) * 5,
                "memory_usage": 30 + (i % 8) * 8,
                "disk_usage": 15 + (i % 6) * 3
            })
        return list(reversed(data))
    except Exception as e:
        st.error(f"获取性能数据失败: {e}")
        return []


def calculate_health_score(system_status: Dict[str, Any]) -> float:
    """计算系统健康度分数"""
    try:
        score = 100.0
        
        # 基础服务检查
        services = system_status.get("services", {})
        total_services = len(services)
        running_services = sum(1 for status in services.values() if status == "running")
        
        if total_services > 0:
            service_score = (running_services / total_services) * 50
            score = service_score + 50
        
        # 智能体状态检查
        active_agents = system_status.get("active_agents", 0)
        total_agents = system_status.get("total_agents", 25)
        
        if total_agents > 0:
            agent_score = (active_agents / total_agents) * 30
            score = min(score, 70 + agent_score)
        
        return max(0, min(100, score))
    except Exception:
        return 50.0


def get_recent_activities() -> List[Dict[str, Any]]:
    """获取最近活动记录"""
    try:
        # 模拟活动数据
        activities = [
            {
                "时间": datetime.now() - timedelta(minutes=5),
                "类型": "数据更新",
                "描述": "股票价格数据同步完成",
                "状态": "成功"
            },
            {
                "时间": datetime.now() - timedelta(minutes=15),
                "类型": "策略执行",
                "描述": "量化策略A执行交易信号",
                "状态": "成功"
            },
            {
                "时间": datetime.now() - timedelta(minutes=30),
                "类型": "风险检查",
                "描述": "投资组合风险评估完成",
                "状态": "正常"
            },
            {
                "时间": datetime.now() - timedelta(hours=1),
                "类型": "系统维护",
                "描述": "缓存清理和优化",
                "状态": "完成"
            }
        ]
        return activities
    except Exception as e:
        st.error(f"获取活动记录失败: {e}")
        return []


if __name__ == "__main__":
    main()